import json
from typing import Any, Optional
import logging
import time

logger = logging.getLogger(__name__)


class CacheService:
    def __init__(self):
        self._memory_cache = {}
        self._cache_expiry = {}  # 存储过期时间
        logger.info("使用内存缓存服务")
    
    def get(self, key: str) -> Optional[Any]:
        """获取缓存数据"""
        try:
            # 检查是否过期
            if key in self._cache_expiry:
                if time.time() > self._cache_expiry[key]:
                    # 过期，删除缓存
                    self._memory_cache.pop(key, None)
                    del self._cache_expiry[key]
                    return None
            
            return self._memory_cache.get(key)
        except Exception as e:
            logger.error(f"获取缓存失败: {e}")
            return None
    
    def set(self, key: str, value: Any, expire: int = 3600) -> bool:
        """设置缓存数据"""
        try:
            self._memory_cache[key] = value
            # 设置过期时间
            self._cache_expiry[key] = time.time() + expire
            return True
        except Exception as e:
            logger.error(f"设置缓存失败: {e}")
            return False
    
    def delete(self, key: str) -> bool:
        """删除缓存数据"""
        try:
            result = self._memory_cache.pop(key, None) is not None
            self._cache_expiry.pop(key, None)
            return result
        except Exception as e:
            logger.error(f"删除缓存失败: {e}")
            return False
    
    def clear_pattern(self, pattern: str) -> int:
        """清除匹配模式的所有缓存"""
        try:
            keys_to_delete = [k for k in self._memory_cache.keys() if pattern.replace('*', '') in k]
            for key in keys_to_delete:
                self._memory_cache.pop(key, None)
                self._cache_expiry.pop(key, None)
            return len(keys_to_delete)
        except Exception as e:
            logger.error(f"清除缓存失败: {e}")
            return 0
    
    def cleanup_expired(self):
        """清理过期的缓存项"""
        current_time = time.time()
        expired_keys = [key for key, expiry in self._cache_expiry.items() if current_time > expiry]
        for key in expired_keys:
            self._memory_cache.pop(key, None)
            del self._cache_expiry[key]
        return len(expired_keys)


# 全局缓存实例
cache_service = CacheService()
